type StorageType = 'localStorage' | 'sessionStorage';

export const LOCAL_STORAGE = 'localStorage'
export const SESSION_STORAGE = 'sessionStorage'

/**
 * 响应式的存储数据
 * @param storageType 存储的位置是localStorage还是sessionStorage
 * @param key 存储的key
 * @param defaultValue  默认值
 */
export const useStorage = <T>(storageType: StorageType, key: string, defaultValue?: T | undefined) => {
  let value: T | undefined = defaultValue;

  if (defaultValue) {
    window[storageType].setItem(key, JSON.stringify(defaultValue));
  } else {
    // 从本地存储中获取值
    const storedValue = window[storageType].getItem(key);
    if (storedValue) {
      try {
        value = JSON.parse(storedValue);
      } catch (error) {
        console.error(`Error parsing stored value for key "${key}":`, error);
      }
    }
  }
  // 使用 Object.defineProperty 监听对象属性的变化
  const storageObject: { value: T } = {value};
  Object.defineProperty(storageObject, 'value', {
    get() {
      return value;
    },
    set(newValue: T) {
      value = newValue;
      window[storageType].setItem(key, JSON.stringify(newValue));
    },
  });

  return storageObject;
}
